/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Visao.Gerente.Relatorios;

import Controle.Controlador;
import Modelo.Relatorio;
import java.text.DateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author Andre Luiz
 */
public class RelatorioPizzas extends javax.swing.JFrame {

    DefaultTableModel modelo1;
    TableRowSorter sorter1;
    Relatorio relatorio;
    
    String dataIni;
    String dataFim;

    /**
     * Creates new form Relatorio
     */
//    public RelatorioPizzas() {
//        initComponents();
//    }

    RelatorioPizzas() {
        initComponents();
        this.relatorio = new Relatorio();
        modelo1 = (DefaultTableModel) jtTabela.getModel();
        dataIni = "01/01/1900";
        dataFim = "01/01/2900";
        //setDadosTela();
        imprimeDadosTabelas();

    }

    public void getDadosVisao() {
        if(validarDadosVisao()){
            relatorio = new Relatorio();
            dataIni = jtDataInicial.getText();
            dataFim = jtDataFinal.getText();
            
            if ("  /  /    ".equals(dataIni)){
                dataIni = "01/01/1900";
            }
            if ("  /  /    ".equals(dataFim)){
                dataFim = "01/01/2900";
            }
        }
    }

    public boolean dataValida(String data) {
        try {
            if ("  /  /    ".equals(data)) {
                return true;
            }
            Date d = DateFormat.getDateInstance().parse(data);
            return true;
        } catch (Exception ex) {
            return false;
        }
    }

    public boolean validarDadosVisao() {
        try {
//            Matcher Lestras = Pattern.compile("[a-zA-Z]").matcher(jTnumeroBuscaDS.getText());
            Matcher Numeros;// = Pattern.compile("[0-9]").matcher();

            // validar a data inicial 
            if (!dataValida(jtDataInicial.getText())) {
                throw new Exception("Erro: Formato Inválido!\nA Data Inicial do Relatório é Inválida\nPreencha o campo no formato: dd/mm/aaaa");
            }
            // validar a data Final 
            if (!dataValida(jtDataFinal.getText())) {
                throw new Exception("Erro: Formato Inválido!\nA Data Final do Relatório é Inválida\nPreencha o campo no formato: dd/mm/aaaa");
            }
            return true;
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(rootPane, ex.getMessage(), "Erro!", 0);
            return false;
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        jtDataInicial = new javax.swing.JFormattedTextField();
        jtDataFinal = new javax.swing.JFormattedTextField();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtTabela = new javax.swing.JTable();
        jbPesquisar = new javax.swing.JButton();
        jbGerarPDF = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("RELATÓRIOS");

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setText("Relatório dos Sabores Mais Vendidos");

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED, java.awt.Color.gray, java.awt.Color.darkGray));
        jPanel1.setPreferredSize(new java.awt.Dimension(652, 77));

        jLabel4.setText("Periodo:");

        try {
            jtDataInicial.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jtDataInicial.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jtDataInicial.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);
        jtDataInicial.setPreferredSize(new java.awt.Dimension(100, 20));

        try {
            jtDataFinal.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jtDataFinal.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jtDataFinal.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);
        jtDataFinal.setPreferredSize(new java.awt.Dimension(100, 20));

        jLabel7.setText("de");

        jLabel8.setText("até");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel7)
                .addGap(2, 2, 2)
                .addComponent(jtDataInicial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(26, 26, 26)
                .addComponent(jLabel8)
                .addGap(18, 18, 18)
                .addComponent(jtDataFinal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(70, 70, 70))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtDataInicial, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel7)
                    .addComponent(jLabel8)
                    .addComponent(jtDataFinal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jtTabela.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Sabor", "Num Vezes"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jtTabela);

        jbPesquisar.setText("Pesquisar");
        jbPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbPesquisarActionPerformed(evt);
            }
        });

        jbGerarPDF.setText("Gerar PDF");
        jbGerarPDF.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbGerarPDFActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 435, Short.MAX_VALUE)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 435, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jbPesquisar)
                            .addComponent(jbGerarPDF)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(77, 77, 77)
                        .addComponent(jLabel1)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(22, 22, 22)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jbPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(50, 50, 50)
                        .addComponent(jbGerarPDF, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 260, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-562)/2, (screenSize.height-504)/2, 562, 504);
    }// </editor-fold>//GEN-END:initComponents

    private void jbGerarPDFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbGerarPDFActionPerformed
        // TODO add your handling code here:
        gerarPDF();
    }//GEN-LAST:event_jbGerarPDFActionPerformed

    private void jbPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbPesquisarActionPerformed
        // TODO add your handling code here:
        if (validarDadosVisao()) {
            getDadosVisao();
            novaPesquisa();
        }
    }//GEN-LAST:event_jbPesquisarActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbGerarPDF;
    private javax.swing.JButton jbPesquisar;
    private javax.swing.JFormattedTextField jtDataFinal;
    private javax.swing.JFormattedTextField jtDataInicial;
    private javax.swing.JTable jtTabela;
    // End of variables declaration//GEN-END:variables

    private boolean getDadosSabores() {
        try {
            relatorio = Controlador.carregarDadosBD_RelSabores(dataIni, dataFim) ;
            if (relatorio != null) {
                return true;
            } else {
                throw new Exception("não foi encontrada nenhuma referencia aos dados de Busca.\nTente novamente!");
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this,e.getMessage() , "Erro!", 0);
            return false;
        }
    }

    private boolean imprimeDadosTabelas() {
        // Adiciona uma nova linha em branco no modelo  
        int linhaTabela1 = 0;
        getDadosSabores();
        if (relatorio == null) {
            return false;
        }
        for (int i = 0; i < relatorio.getRelSabores().size(); i++) {

            if (jtTabela.getRowCount() <= linhaTabela1) {
                modelo1.addRow(new String[]{"", ""});
            }
            jtTabela.setValueAt(relatorio.getRelSabores().get(i).getSabor(), linhaTabela1, 0);
            jtTabela.setValueAt(relatorio.getRelSabores().get(i).getNum(), linhaTabela1, 1);

            linhaTabela1++;

        }
        removeLinhasInutilizadas(linhaTabela1);
        return true;
    }

    public void removeLinhasInutilizadas(int inicioTab1) {
        for (int i = inicioTab1; i < jtTabela.getRowCount(); i++) {
            modelo1.removeRow(i);
        }
    }

    public void LimparTabela() {
        while (jtTabela.getRowCount() > 0) {
            modelo1.removeRow(0);
        }
    }

    public void novaPesquisa() {
        LimparTabela();
        imprimeDadosTabelas();
    }

    public void gerarPDF() {

    }
}
